<template>
  <n-modal
    :show="showModal"
    preset="dialog"
    :title="title"
    :closable="false"
    positive-text="确认"
    negative-text="取消"
    @positive-click="submitCallback"
    @negative-click="close"
    @on-update:show="close"
  >
    <n-form ref="formRef" :model="formData" :rules="rules">
      <n-form-item label="团队名称" path="name">
        <n-input v-model:value="formData.name" />
      </n-form-item>
      <n-form-item label="团队简介" path="introduce">
        <n-input v-model:value="formData.introduce" />
      </n-form-item>
      <n-form-item label="团队成员" path="">
        <n-select
          v-model:value="formData.members"
          :options="userOptions"
          multiple
          filterable
          placeholder="请选择团队成员"
        />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import type { UserModel } from "@/api/user/model";
import type { TeamModel } from "@/api/team/model";
import { NModal, NForm, NFormItem, NInput, NSelect } from "naive-ui";
import type { CreateTeamParams } from "@/api/team/type";
import { message } from "@/utils/message";
import { getUserList } from "@/api/user";
import { createTeam } from "@/api/team";
import type { FormInst } from "naive-ui";

const props = defineProps<{
  showModal: boolean;
  currentTeam: TeamModel;
  type: "add" | "edit";
}>();

const emit = defineEmits<{
  (event: "update:showModal", value: boolean): void;
  (event: "submitCallback"): void;
}>();

const formRef = ref<FormInst | null>(null);
const formData = ref<CreateTeamParams>({
  id: 0,
  name: "",
  introduce: "",
  members: [],
});
const members = ref<UserModel[]>([]);
const rules = {
  name: {
    required: true,
    message: "请输入团队名称",
  },
};

const title = computed(() => {
  return props.type === "add" ? "新建团队" : "编辑团队";
});

const userOptions = computed(() => {
  return members.value.map((item) => {
    return {
      label: item.nickname,
      value: item.id,
    };
  });
});

const close = () => {
  emit("update:showModal", false);
};

const submitCallback = () => {
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const res = await createTeam(formData.value);
      if (res.code != 200) {
        message.error(res.message);
        return;
      }
      close();
      emit("submitCallback");
    }
  });
};

onMounted(async () => {
  const res = await getUserList();
  if (res.code === 200) {
    members.value = res.data;
  } else {
    message.error(res.message);
  }
});

watch(
  () => props.currentTeam,
  (val) => {
    if (val) {
      formData.value = {
        id: val.id,
        name: val.name,
        introduce: val.introduce,
        members: val.members.filter((item) => item.id).map((item) => item.id!),
      };
    }
  },
  { immediate: true },
);
</script>
